package com.netdimensions.confluence.plugins;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;

/**
 * Created by IntelliJ IDEA.
 * User: Rob
 * Date: 1/17/11
 * Time: 2:35 AM
 * To change this template use File | Settings | File Templates.
 */
public final class Parameter {
    public final String name;
    public final String value;

    public Parameter(final String name, final String value) {
        this.name = name;
        this.value = value;
    }

    private static final String encoded(final String s) {
        try {
            return URLEncoder.encode(s, "UTF-8");
        } catch (final UnsupportedEncodingException e) {
            throw new AssertionError("Required encoding UTF-8 is unsupported.");
        }
    }

    public final String toString() {
        return encoded(name) + "=" + encoded(value);
    }

    public static final String encoded(final Iterable<Parameter> parameters) {
        if (isEmpty(parameters)) {
            return "";
        } else {
            final StringBuilder result = new StringBuilder(parameters.iterator().next().toString());

            for (final Parameter p : tail(parameters)) {
                result.append('&');
                result.append(p.toString());
            }

            return result.toString();
        }
    }

    private static final <T> Iterable<T> tail(final Iterable<T> xs) {
        return new Iterable<T>() {
            public final Iterator<T> iterator() {
                final Iterator<T> result = xs.iterator();
                result.next();
                return result;
            }
        };
    }

    private static final boolean isEmpty(final Iterable<?> xs) {
        return !xs.iterator().hasNext();
    }
}
